<?php
/**
 * Created by PhpStorm.
 * User: Tyler
 * Date: 2018/5/2
 * Time: 10:47
 */

namespace App\Logic;

use App\Common\HttpClient;
use App\Common\Logger;
use Illuminate\Support\Facades\DB;

class SpreadLogic extends Base
{
    //与身份证验证有关的数据
    protected $showapi_appid = '63384';
    protected $showapi_secret = 'c9369aafff3e4777ac945c7e46cd4877';
    protected $download_url_base = 'http://www.heroscocks.com/download/index.html?'
    protected $qrcode_url_base = 'http://pan.baidu.com/share/qrcode?w=600&h=600&url='

    //有用户消费，查看并发送返点
    public function Kickback($uid, $type, $num, $desc = ''){
        $spreader = $this->getSpreaderOfUser($uid);
        if($spreader == null){
            return;
        }else{
            DB::table('t_kickback_rec')
                ->insert([''])
        }

    }
    //完善身份信息
    public function fillIdentity($uid, $phone, $identity, $realname = '')
    {
        $paramArr = ['realname' => $realname, 'phone' => $phone, 'identity' => $identity];
        if(empty($phone)) {
            throw new ApiException('手机号码不能为:' . $phone . ' uid:' . $uid, 2);
        }
        if(empty($identity)){
            throw new ApiException('身份证号码不能为:'.$identity.' uid:'.$uid, 2);
        }
        if (!DB::table('t_player_info')->where('id', $uid)->update($paramArr)) {
            throw new ApiException('完善用户信息失败', 1);
        }
    }
    //申请提现
    public function applyWithdraw($uid, $num, $target, $type=1){
        DB::beginTransaction();
        try{
            $list = DB::table('t_spread_info')->where('uid', $uid)->first()->lockForUpdate();
            if(empty($list)){
                throw new ApiException('该用户不是代理人，请提交申请', 1);
            }
            $card = '';
            switch ($target) {
                case 1:
                    $card = $list->wechat;
                    break;
                case 2:
                    $card = $list->alipay;
                    break;
                case 3:
                    $card = $list->bank_card;
                    break;
                default:
                    {
                        DB::rollBack();
                        throw new ApiException('请选择合法的支付类型', 1);
                    }
            }
            if (empty($card)){
                DB::rollBack();
                throw new ApiException('您未绑定您所选择的支付方式，请前往绑定', 1);
            }
            $updateParam = [];
            $type_str = '';
            if($type == 1){
                $updateParam['rmb'] = int($list['rmb']) - $num;
                $type_str = 'rmb';
            } elseif ($type == 2){
                $updateParam['diamonds'] = int($list['diamonds']) - $num;
                $type_str = 'diamonds';
            }else{
                DB::rollBack();
                throw new ApiException('请选择合法的套现类型', 1);
            }
            if(1 != DB::table('t_spread_info')
                ->where('id',$list->id)
                ->where($type_str,'>=',$num)
                ->update($updateParam))
            {
                DB::rollBack();
                throw new ApiException('更新返点金额失败', 1);
            }
            DB::table('t_withdraw_rec')->insert([
                'spreader' => $list->id,
                'type' => $type,
                'target' => $target,
                'number' => $num,
                'desc' => $card
            ]);
            DB::commit();
        }
        catch(\Exception $exception) {
            DB::rollBack();
            Logger::instance()->setErrorLog($exception);
        }
    }

    //获取代理人信息
    public function spreaderInfo($uid){
        try{
            $list = DB::table('t_spread_info')
                ->where('uid',$uid)
                ->where('status',1)
                ->first(['*']);
            if (empty($list)){
                throw new ApiException('该用户不是代理人，请提交申请', 1);
            }
            $shared_url = $this->download_url_base.'spreader='.str($list['id']);
            $list['spread_id'] = $list['id'];
            $list['shared_url'] = $shared_url;
            $list['code_url'] = $this->qrcode_url_base.$shared_url;
            return $list;
        }
        catch(\Exception $exception) {
            Logger::instance()->setErrorLog($exception);
        }
    }

    //查看代理人团队用户 filter 过滤会员等级 -1.全量 0.普通用户 1-N.VIP等级 默认-1
    public function spreadTeaminfo($spreader, $length = 10, $filter=-1, $page=1){
        $userList = [];
        $members = $this->getAllUserFromSpreader($spreader);
        foreach ($members as $member){
            $uid = $member->uid;
            $userinfo = $this->get_user_info($uid);
            if($userinfo == false){
                continue;
            }
            $user_info = ['uid' => $uid];
            $vip = $this->getVipLevel($uid);
            if($filter != -1 && $vip != $filter){
                continue;
            }
            $user_info['vip_level'] = $vip;
            $user_info['nickname'] = $userinfo.nick_name;
            $user_info['phone_num'] = $userinfo.phone;
            $user_info['identity_card'] = $userinfo.identity;
            $user_info['rmb'] = $this->getUserForSpreader($uid,$spreader,1);
            $user_info['diamonds'] = $this->getUserForSpreader($uid,$spreader,2);
            $user_info['create_time'] = $userinfo.create_time;
            $user_info['update_time'] = $userinfo.update_time;
            $userList[] = $user_info;
        }
        $user_count = count($userList);
        $page_count = $user_count / $length + ($user_count % $length == 0)?0:1;
        return ['user_list' => array_slice($userList,($page-1)*$length,$length), 'user_count' => $user_count, 'total_page' => $page_count];
    }

    //查看返点记录
    public function kickbackRecord($spreader, $uid, $length, $filter, $page){
        $kickback_list = [];
        $recs = $this->getKickbackRecord($filter,$spreader,$uid);
        foreach ($recs as $rec) {
            $kickback_rec = [];
            $kickback_rec['id'] = $rec->id;
            $kickback_rec['type'] = $rec->type;
            $kickback_rec['desc'] = $rec->desc;
            $kickback_rec['num'] = $rec->number;
            $kickback_rec['uid'] = $rec->uid;
            $kickback_rec['create_time'] = $rec->create_time;
            $kickback_list[] = $kickback_rec;
        }
        $user_count = count($kickback_list);
        $page_count = $user_count / $length + ($user_count % $length == 0)?0:1;
        return ['kickback_list' => array_slice($kickback_list,($page-1)*$length,$length), 'user_count' => $user_count, 'total_page' => $page_count];
    }

    //查看套现记录
    public function WithdrawRecord($uid, $length, $filter, $page){
        $withdraw_list = [];
        $recs = $this->getWithdrawRecord($filter,$uid);
        foreach ($recs as $rec) {
            $withdraw_rec = [];
            $withdraw_rec['id'] = $rec->id;
            $withdraw_rec['type'] = $rec->type;
            $withdraw_rec['desc'] = $rec->desc;
            $withdraw_rec['num'] = $rec->number;
            $withdraw_rec['target'] = $rec->target;
            $withdraw_rec['status'] = $rec->status;
            $withdraw_rec['create_time'] = $rec->create_time;
            $withdraw_rec['update_time'] = $rec->update_time;
            $withdraw_list[] = $withdraw_rec;
        }
        $user_count = count($withdraw_list);
        $page_count = $user_count / $length + ($user_count % $length == 0)?0:1;
        return ['withdraw_list' => array_slice($withdraw_list,($page-1)*$length,$length), 'user_count' => $user_count, 'total_page' => $page_count];
    }

    //获取用户VIP等级
    protected function getVipLevel($uid){
        try{
            $user = DB::table('t_vip_info')
                ->where('uid',$uid)
                ->where('status',1)
                ->where('expire_time', '>' , DB::raw('NOW()'))
                ->first('vip_conf_id');
            if(!empty($user)){
                return $user->vip_conf_id;
            }
            return 0;
        }
        catch(\Exception $exception) {
            Logger::instance()->setErrorLog($exception);
        }
    }

    //获取套现记录
    protected function getWithdrawRecord($type, $spreader){
        $whereParam = [['spreader',$spreader]];
        if($type != 0){
            $whereParam[] = ['type', $type];
        }
        try{
            $recs = DB::table('t_withdraw_rec')
                ->where($whereParam)
                ->orderByDesc('id')
                ->get();
            return $recs;
        }
        catch(\Exception $exception) {
            Logger::instance()->setErrorLog($exception);
        }
    }

    //获取返点记录
    protected function getKickbackRecord($type, $spreader, $uid = 0){
        $whereParam = [['spreader',$spreader]];
        if($uid != 0){
            $whereParam[] = ['uid',$uid];
        }
        if($type != 0){
            $whereParam[] = ['type',$type];
        }
        try{
            $recs = DB::table('t_kickback_rec')
                ->where($whereParam)
                ->orderByDesc('id')
                ->get();
            return $recs;
        }
        catch(\Exception $exception) {
            Logger::instance()->setErrorLog($exception);
        }
    }

    //获取该用户所属的代理人
    protected function getSpreaderOfUser($uid){
        try{
            $spreader = DB::table('t_spread_members_info')
                ->where('uid',$uid)
                ->first('spreader');
            return $spreader;
        }
        catch(\Exception $exception) {
            Logger::instance()->setErrorLog($exception);
        }
    }

    //获取代理人下所有用户
    protected function getAllUserFromSpreader($spreader)
    {
        try{
            $members = DB::table('t_spread_members_info')
                ->where('spreader',$spreader)
                ->select('uid')->get('uid');
            return $members;
        }
        catch(\Exception $exception) {
            Logger::instance()->setErrorLog($exception);
        }
    }
    //获取某用户为某代理人贡献了多少返点
    protected function getUserForSpreader($uid, $spreader, $type)
    {
        try
        {
            return DB::table('t_kickback_rec')
                ->where([['type',$type],['uid',$uid],['spreader',$spreader]])
                ->max('number');
        }
        catch(\Exception $exception)
        {
            Logger::instance()->setErrorLog($exception);
        }
    }

    //完善代理人支付信息
    public function fillSpreaderPayInfo($spreader, $wechat = '', $alipay = '', $bank_card = '')
    {
        $paramArr = [];
        if(!empty($wechat))$paramArr['wechat'] = $wechat;
        if(!empty($alipay))$paramArr['alipay'] = $alipay;
        if(!empty($bank_card))$paramArr['bank_card'] = $bank_card;
        if(!$paramArr->isEmpty()){
            try{
                if (!DB::table('t_spread_info')->where('uid', $spreader)->update($paramArr)) {
                    throw new ApiException('更新支付信息失败', 1);
                }
            }
            catch(\Exception $exception) {
                Logger::instance()->setErrorLog($exception);
            }
        }
    }

    //检查身份证真伪
    public function checkIdentity($identity)
    {
        if (empty($identity)){
            throw new ApiException('身份证号为空', 1);
        }
        $paramArr = array(
            'showapi_appid'=> $this->showapi_appid,
            'id'=> $identity
        );
        $url = $this->identitySign($paramArr);
        for($i=0; $i<10; $i++){
            $result = HttpClient::Get($url);
            if ($result == false){
                throw new ApiException('身份证验证服务器错误', 3);
            }
            $find = json_decode($result);
            if($find->showapi_res_code != 0)
            {
                continue;
            }
            if($find->showapi_res_body->ret_code == 0 &&
                $find->showapi_res_body->retMsg == 'success') {
                return;
            }
            else{
                throw new ApiException('身份证不合法', 3);
            }
        }
        throw new ApiException('身份证验证服务器资源紧张，请重试', 3);
    }

    //检查身份证的签名
    protected function identitySign ($paramArr) {
        $paraStr = "";
        $signStr = "";
        ksort($paramArr);
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $signStr .= $key.$val;
                $paraStr .= $key.'='.urlencode($val).'&';
            }
        }
        $signStr .= $this->showapi_secret;//排好序的参数加上secret,进行md5
        $sign = strtolower(md5($signStr));
        $paraStr .= 'showapi_sign='.$sign;//将md5后的值作为参数,便于服务器的效验
        return $paraStr;
    }

    //新建一个代理用户 return spreader_id
    public function newSpread($uid)
    {
        try {
            $list = DB::table('t_spread_info')->where('uid', $uid)->first(['id']);
            if (!empty($list)) {
                return $list->id;
            }
            return DB::table('t_spread_info')->insertGetId([
                'uid' => $uid
            ]);
        } catch (\Exception $exception) {
            Logger::instance()->setErrorLog($exception);
        }
    }
}